<template>
    <a-modal title="新建预发布版本" centered v-model:visible="visible" cancelText="取消" okText="保存" @ok="handleOk">
        <div>
            <a-form layout="inline" :model="form" ref="ruleFormRef" :rules="rules">
                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item label="所属产品" name="system">
                            <div>
                                <h-search-select-cell
                                    :default-value="
                                        catalogCode
                                            ? $filters.valToNameFilter('fromSystem', catalogCode)
                                            : $filters.valToNameFilter('fromSystem', form.system)
                                    "
                                    type="mySystem"
                                    label="system"
                                    @success="handleSelectChange"
                                />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="版本号" name="versionNumber">
                            <flexbox v-if="systemInfo.catalogCode">
                                <a-select
                                    v-model:value="form.versionNumber"
                                    @change="handleSelectVersionNumber"
                                    style="width: 120px; margin-right: 8px"
                                    v-if="versionNumberList.length"
                                >
                                    <a-select-option :key="item.versionNumber" v-for="item of versionNumberList">
                                        <HToolTip :title="item.versionNumber">
                                            <span>{{ item.versionNumber }}</span>
                                        </HToolTip>
                                    </a-select-option>
                                </a-select>
                                <flexbox>
                                    <a class="margin-l-8" @click="handleCreateCal">前往【版本管理】新建版本号</a>
                                </flexbox>
                            </flexbox>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="版本名称" name="versionName">
                            <a-input
                                v-model:value="form.versionName"
                                :disabled="!form.system"
                                placeholder="请输入版本名称限制200个字"
                                :maxlength="200"
                                allow-clear
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :span="24">
                        <a-form-item label="预计交付日期" name="expectTime">
                            <div style="width: 100%" v-if="visible">
                                <span v-if="versionNumberList.length"> {{ $filters.dateFilter(form.expectTime) }} </span>
                                <h-date-picker-cell :disabledDate="false" v-model:value="form.expectTime" v-else />
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="20">
                        <a-form-item label="流程类型" name="processType">
                            <div style="width: 100%" v-if="form.system">
                                <span v-if="form.systemType !== '3'">
                                    {{ $filters.valToNameFilter('processType', form.processType) }}
                                </span>
                                <div v-else>
                                    <a-select placeholder="请选择" v-model:value="form.processType">
                                        <a-select-option v-for="item of dicOptions.processType" :key="item.code">
                                            {{ item.dimensionName }}
                                        </a-select-option>
                                    </a-select>
                                </div>
                            </div>
                        </a-form-item>
                    </a-col>
                    <a-col :span="24" v-if="form.processType === '1'">
                        <a-form-item label="交付模式" name="deliveryMode">
                            <div style="width: 100%">
                                <a-select placeholder="请选择" v-model:value="form.deliveryMode">
                                    <a-select-option key="1"> 项目模式 </a-select-option>
                                    <a-select-option key="2"> 迭代模式 </a-select-option>
                                </a-select>
                            </div>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
    </a-modal>
</template>

<script lang="ts">
import moment from 'moment';
import api from '@/api';
import { useRouter } from 'vue-router';
import { reg1 } from '@/config/pattern';
import { HDatePickerCell, HSearchSelectCell } from '@/components';
import { message } from 'ant-design-vue';
import HToolTip from '@/components/HToolTip/index.vue';
import store from '@/store';
import { defineComponent, ref, unref, reactive, toRefs, nextTick, computed, onDeactivated } from 'vue';
export default defineComponent({
    name: 'CreateVersion',
    components: {
        HDatePickerCell,
        HSearchSelectCell,
        HToolTip
    },
    emits: ['success'],
    setup(_, { emit }) {
        const router = useRouter();
        const ruleFormRef = ref<any>();
        const state = reactive<any>({
            visible: false,
            form: {
                versionNumber: '',
                versionName: '',
                expectTime: '',
                system: null,
                pmpVersionManagementDTO: null,
                catalogCode: '',
                processType: null,
                deliveryMode: '',
                systemType: null
            },

            versionNumberList: [],
            isRepeatNumber: false,
            catalogCode: null,
            systemInfo: {}
        });
        const validateRepeatNumber = async (rule: any, value: any) => {
            if (value) {
                const { system } = state.form;
                const query = {
                    system,
                    versionNumber: value
                };
                const { success, errorMsg } = await api.versionModel.validVersionRepeat(query, { cancelDuplicated: true });
                return success ? Promise.resolve() : Promise.reject(errorMsg);
            } else {
                return Promise.reject('版本号不能为空');
            }
        };
        const validateRepeatName = async (rule: any, value: any) => {
            if (value) {
                const { system } = state.form;
                const query = {
                    system,
                    versionName: value
                };
                const { success, errorMsg } = await api.versionModel.validVersionRepeat(query, { cancelDuplicated: true });
                return success ? Promise.resolve() : Promise.reject(errorMsg);
            } else {
                return Promise.reject('版本名称不能为空');
            }
        };
        const validateSystem = async (rule: any, value: any) => {
            if (value) {
                const res = state.systemInfo.isOutsideSystem === '0';
                return res ? Promise.resolve() : Promise.reject('外部产品暂不支持创建版本');
            } else {
                return Promise.reject('所属产品不能为空');
            }
        };

        const rules = computed(() => {
            const rules: any = {
                versionNumber: [{ required: true, validator: validateRepeatNumber, trigger: 'change' }],
                versionName: [{ required: true, validator: validateRepeatName, trigger: 'blur' }],
                expectTime: state.versionNumberList.length ? [] : [{ required: true, message: '预计交付日期不能为空', trigger: 'blur' }],
                system: [{ required: true, validator: validateSystem, trigger: 'change', type: 'number' }],
                deliveryMode: [{ required: true, message: '交付模式不能为空', trigger: 'blur' }]
            };
            if (state.form.systemType === '3') {
                rules.processType = [{ required: true, message: '流程类型不能为空', trigger: 'blur' }];
            }
            return rules;
        });

        const handleSelectVersionNumber = (val) => {
            const item = state.versionNumberList.find((item) => item.versionNumber === val);
            state.form.pmpVersionManagementDTO = item || null;
            state.form.expectTime = item.onlineTime ? moment(item.onlineTime).format('YYYY-MM-DD HH:mm:ss') : item.onlineTime;
        };
        // 重新定义数据
        const initData = (val) => {
            state.catalogCode = val.catalogCode;
            state.form.system = val.systemId;
            state.form.catalogCode = '';
            state.form.systemType = val.systemType;
            if (val.systemType !== '3') {
                state.form.processType = state.form.systemType;
            }
            handleChangeSystem();
        };
        // 获取系统详情
        const getSystemInfo = async () => {
            const query = {
                id: state.form.system
            };
            // 获取系统信息
            const { success, moule } = await api.productDetailModel.findById(query);
            if (success) {
                state.systemInfo = {
                    ...moule
                };
                initData({
                    ...moule,
                    systemId: state.form.system
                });
            }
        };
        // 选择系统
        const handleSelectChange = (val) => {
            console.log('val', val);
            state.systemInfo = {
                ...val
            };
            initData(val);
        };
        // 搜索产品下所有可用的上线版本号
        const handleChangeSystem = async () => {
            unref(ruleFormRef) && unref(ruleFormRef).clearValidate();
            state.isRepeatNumber = false;
            getVersionNumberList();
        };
        // 搜索系统下的所有可用的版本号
        const getVersionNumberList = async () => {
            const { success, moule, errorMsg } = await api.versionControlModel.findUsableVersions({
                catalogCode: state.catalogCode
            });
            if (success) {
                state.versionNumberList = [...moule];
            } else {
                message.error(errorMsg);
            }
        };
        // 校验提测名称是否包含特殊字符，因为word和excel文件名不允许特殊字符，交付物的名称是以需求名称创建的
        const validateTestNumber = (rule, value) => {
            if (value) {
                return reg1.test(value) ? Promise.reject('版本号只能输入数字和英文和特殊符号') : Promise.resolve();
            } else {
                return Promise.reject('版本号不能为空');
            }
        };

        const handleOk = () => {
            unref(ruleFormRef)
                .validate()
                .then(() => {
                    handleSave();
                })
                .catch((err: any) => {
                    console.log(err);
                });
        };
        const handleSave = async () => {
            const query = {
                ...state.form,
                createUserEmpId: store.getters.userInfo.employeeDTO.empId,
                createUser: store.getters.userInfo.employeeDTO.name
            };
            const { success, errorMsg } = await api.versionModel.save(query);
            state.visible = false;
            if (success) {
                message.success('保存成功');
                emit('success');
            } else {
                message.error(errorMsg);
            }
        };
        const handleCreateCal = () => {
            state.visible = false;
            router.push({
                path: '/productAnalysis/versionControl',
                query: {
                    catalogCode: state.systemInfo.catalogCode,
                    catalogType: state.systemInfo.catalogType
                }
            });
        };
        const open = (system: Nullable<number>) => {
            state.visible = true;
            nextTick(() => {
                unref(ruleFormRef).clearValidate();
            });
            state.form = {
                versionNumber: '',
                versionName: '',
                expectTime: '',
                pmpVersionManagementDTO: null,
                catalogCode: '',
                system
            };
            state.catalogCode = null;
            state.versionNumberList = [];
            state.systemInfo = {};
            if (system) {
                getSystemInfo();
            }
        };

        onDeactivated(() => {
            state.visible = false;
        });

        return {
            ruleFormRef,
            ...toRefs(state),
            rules,
            open,
            handleOk,
            handleChangeSystem,
            handleSelectVersionNumber,
            handleCreateCal,
            handleSelectChange
        };
    }
});
</script>